package com.usian.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.model.admin.dtos.NewsAuthDto;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmNewsDto;
import com.usian.model.media.dtos.WmNewsPageReqDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNews;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.mapper.WmUserMapper;
import com.usian.wemedia.service.WmNewsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {


    @Value("${fileServerUrl}")
    private String fileServerUrl;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private KafkaTemplate kafkaTemplate;
    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Autowired
    private WmUserMapper wmUserMapper;


    @Override
    public ResponseResult findNewsList(WmNewsPageReqDto dto) {

        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();

        //查询条件
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (dto.getStatus() != null) {
            lambdaQueryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        if (StringUtils.isNotBlank(dto.getKeyword())) {
            lambdaQueryWrapper.like(WmNews::getTitle, dto.getKeyword());
        }
        if (dto.getChannelId() != null) {
            lambdaQueryWrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) {
            lambdaQueryWrapper.between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }

        WmUser wmUser = WmThreadLocalUtils.getUser();
        Integer userId = null;
        if (wmUser != null) {
            userId = wmUser.getId();
        }
        if (userId != null) {
            lambdaQueryWrapper.eq(WmNews::getUserId, userId);
        }
        lambdaQueryWrapper.orderByDesc(WmNews::getCreatedTime);

        //执行查询
        Page page = new Page(dto.getPage(), dto.getSize());
        IPage result = this.page(page, lambdaQueryWrapper);

        //封装
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) result.getTotal());
        responseResult.setData(result.getRecords());
        responseResult.setHost(fileServerUrl);

        return responseResult;
    }


    public static final Short COLLECT_MATERIAL = 1;//收藏
    public static final Short CANCEL_COLLECT_MATERIAL = 0;//收藏
    public static final String WM_NEWS_TYPE_IMAGE = "image";
    public static final Short WM_NEWS_NONE_IMAGE = 0;
    public static final Short WM_NEWS_SINGLE_IMAGE = 1;
    public static final Short WM_NEWS_MANY_IMAGE = 3;
    public static final Short WM_NEWS_TYPE_AUTO = -1;
    public static final Short WM_CONTENT_REFERENCE = 0;
    public static final Short WM_COVER_REFERENCE = 1;
    public static final short WM_NEWS_CONTENT_REFERENCE = 1;//主图引用


    @Override
    public ResponseResult saveNews(WmNewsDto dto, Short isSubmit) {

        /**
         * wmnew    wmmateical   wmnewmatical
         */

        //1:校验参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2：构建 wmnews对象
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);

        //封面类型为自动 设置为空
        if (WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            wmNews.setType(null);
        }
        //设置封面图片格式
        if (dto.getImages() != null && dto.getImages().size() > 0) {
            String replace = dto.getImages().toString().replace("[", "")
                    .replace("]", "").replace(fileServerUrl, "")
                    .replace(" ", "");

            wmNews.setImages(replace);
        }

        //保存
        this.mergeNers(wmNews, isSubmit);

        //文章和素材关系表 wmnewsmatical  ，过滤封面和内容中图片地址
        String content = dto.getContent();
        List<Map> list = JSON.parseArray(content, Map.class);
        // 文章中的封面和内容中 图片路径
        List<String> stringList = this.ectractUrlInfo(list);


        //处理内容图片和素材关系
        if (isSubmit == 1 && stringList.size() > 0) {

            boolean b = this.saveRelativeInfoForContent(stringList, wmNews, 0);
            if (!b) {
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
            }
        }

        //处理封面图片和素材关系
        if (isSubmit == 1) {

            boolean b = this.saveRelativeInfoForCover(dto, stringList, wmNews);
            if (!b) {
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
            }

        }


        //保存完毕文章自动审核
        kafkaTemplate.send("newsScan",wmNews.getId().toString());

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult findNewsById(Integer newsId) {
        if (newsId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        WmNews wmNews = this.getById(newsId);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        ResponseResult responseResult = new ResponseResult();
        responseResult.setHost(fileServerUrl);
        responseResult.setData(wmNews);

        return responseResult;
    }

    //处理封面和素材关系
    private boolean saveRelativeInfoForCover(WmNewsDto dto, List<String> materials, WmNews wmNews) {
        boolean result = false;

        Short type = dto.getType();
        List<String> images = dto.getImages();


        if (type.equals(WM_NEWS_TYPE_AUTO)) {
            //内容中的图片数量小于等于2  设置为单图
            if (materials.size() > 0 && materials.size() <= 2) {
                wmNews.setType(WM_NEWS_SINGLE_IMAGE);
                images = materials.stream().limit(1).collect(Collectors.toList());
            } else if (materials.size() > 2) {
                //如果内容中的图片大于2 则设置为多图
                wmNews.setType(WM_NEWS_MANY_IMAGE);
                images = materials.stream().limit(3).collect(Collectors.toList());
            } else {
                //内容中没有图片，则是无图
                wmNews.setType(WM_NEWS_NONE_IMAGE);
            }
        }

        //过滤封面图片中的字段
        if (images != null && images.size() > 0) {
            wmNews.setImages(images.toString().replace("[", "")
                    .replace("]", "").replace(fileServerUrl, "")
                    .replace(" ", ""));

        }

        //1:修改主表 wmnews images  2：维护关系表
        this.updateById(wmNews);

        boolean b = this.saveRelativeInfoForContent(images, wmNews, 1);

        return b;
    }


    //处理内容图片和素材关系
    private boolean saveRelativeInfoForContent(List<String> stringList, WmNews wmNews, Integer type) {
        boolean result = false;
        //先到素材表查询图片  集合   当前登录用户
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        if (stringList.size() > 0) {
            lambdaQueryWrapper.in(WmMaterial::getUrl, stringList);
        }
        WmUser user = WmThreadLocalUtils.getUser();
        Integer userId = null;
        if (user != null) {
            userId = user.getId();
        }
        lambdaQueryWrapper.eq(WmMaterial::getUserId, userId);
        List<WmMaterial> materialList = wmMaterialMapper.selectList(lambdaQueryWrapper);


        List<String> materialsIds = new ArrayList<>();  //素材id
        if (materialList.size() > 0) {
            //把素材库 materialList 转map
            Map<String, Integer> MaterialMap = materialList.stream().collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));

            //二次过滤  比较两个集合 materialList  MaterialMap 取 存在
            for (WmMaterial w : materialList) {
                Integer value = MaterialMap.get(w.getUrl());
                if (value != null) {
                    materialsIds.add(value.toString());
                }
            }
        }

        //批量保存
        if (materialsIds.size() > 0) {
            wmNewsMaterialMapper.saveRelationsByContent(materialsIds, wmNews.getId(), type);
        }

        result = true;
        return result;
    }

    //解析文章内容中的图片和素材库中关联
    private List<String> ectractUrlInfo(List<Map> list) {

        List<String> materials = new ArrayList<>();
        for (Map map : list) {

            if (map.get("type").equals(WM_NEWS_TYPE_IMAGE)) {
                //类型是图片
                String imgUrl = (String) map.get("value");
                imgUrl = imgUrl.replace(fileServerUrl, "");
                materials.add(imgUrl);
            }
        }

        return materials;
    }

    //保存主表 wmnews
    private void mergeNers(WmNews wmNews, short isSubmit) {
        wmNews.setStatus(isSubmit);

        WmUser user = WmThreadLocalUtils.getUser();
        Integer userId = null;
        if (user != null) {
            userId = user.getId();
        }
        wmNews.setUserId(userId);
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable((short) 0);
        //保存 修改
        if (wmNews.getId() == null) {
            this.save(wmNews);
        } else {
            //修改  子表 关系删除掉
            LambdaQueryWrapper<WmNewsMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(WmNewsMaterial::getNewsId, wmNews.getId());
            wmNewsMaterialMapper.delete(lambdaQueryWrapper);
            //修改
            this.updateById(wmNews);
        }
    }


    @Override
    public ResponseResult delNews(Integer id) {
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        WmNews wmNews = getById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //发布的和上架的不能删除
        if (wmNews.getStatus()==9&& wmNews.getEnable()==1) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //删除关系
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));

        //删除文章
        removeById(wmNews.getId());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        if(dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        WmNews wmNews = getById(dto.getId());
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //发布（9）的文章不能上下架
        if(wmNews.getStatus()!=9){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        if(dto.getEnable() != null && dto.getEnable() > -1 && dto.getEnable() < 2){
            update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,dto.getId()).set(WmNews::getEnable,dto.getEnable()));
        }


        //上下架后发kafka消息通知aparticle服务上下架文章

        if(wmNews.getEnable()!=null &&(wmNews.getEnable()==1 || wmNews.getEnable()==0)) {
            Map<String, Object> map = new HashMap<>();
            map.put("articleId", wmNews.getArticleId());
            map.put("enable", wmNews.getEnable());
            kafkaTemplate.send("enableNews", JSON.toJSONString(map));
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public List<Integer> findNewsListShenhe() {
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper =new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WmNews::getStatus,8);
        lambdaQueryWrapper.lt(WmNews::getPublishTime,new Date());
        List<Integer> wmNewsList = this.list(lambdaQueryWrapper).stream().map(WmNews::getId).collect(Collectors.toList());
        return wmNewsList;
    }

    @Override
    public PageResponseResult findNewsRenGongPage(NewsAuthDto dto) {

        dto.checkParam();
        dto.setPage((dto.getPage()-1)*dto.getSize());

        List<WmNews> wmNewsList = wmNewsMapper.findList(dto);
        int count = wmNewsMapper.findListCount(dto);

        PageResponseResult result =new PageResponseResult(dto.getPage(),dto.getSize(),count);
        result.setData(wmNewsList);

        return result;
    }

    @Override
    public ResponseResult findOne(Integer id) {

        if(id ==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = this.getById(id);

        if(wmNews!=null){
            WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
            if(wmUser!=null){
                wmNews.setAuthorName(wmUser.getName());
            }
        }



        return ResponseResult.okResult(wmNews);
    }

    @Override
    public ResponseResult authNewsRenGong(NewsAuthDto dto) {

        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        WmNews wmNews = this.getById(dto.getId());
        if(wmNews!=null){
            //type 0 未通过  1通过
            if(dto.getStatus()==2){
                wmNews.setReason(dto.getMsg());
            }
            wmNews.setStatus(dto.getStatus());
            this.updateById(wmNews);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
